#!c:\python25\python.exe
from string import *
from xml.sax import parse, SAXParseException, ContentHandler
import os

class ParserHandler( ContentHandler ):
    def __init__( self, fp ):
        ContentHandler.__init__( self )
        self.fileFP = fp
        self.iDepth = 0
        self.bStructFg = False
        self.caName = ''
        self.cType = ''
        self.iLength = 0
        self.caValueName = ''
        self.caType = ''

    def startElement( self, name, attributes ):
        if lower(name) == "record":
            for attrName in attributes.getNames():
                self.caType = attributes.getValue(attrName)
                if attrName == "type" and attributes.getValue(attrName) == "Detail":
                    self.bStructFg = True
                    self.iDepth = 4
                    self.fileFP.write("typedef struct \n{\n")
        elif ( self.bStructFg == True and lower(name) == "field" ):
            for attrName in attributes.getNames():
                if attrName == "name":
                    self.caName = attributes.getValue(attrName)
                elif attrName == "type":
                    self.cType = attributes.getValue(attrName)
                elif attrName == "length":
                    self.iLength = int(attributes.getValue(attrName))

            if self.cType[0] == 'C':
                self.caValueName = "ca" + ( self.caName + "[%d + 1];" % self.iLength )
                self.caValueName = ("%s" % " " * self.iDepth) + "char    " + self.caValueName
            elif self.cType[0] == 'N':
                self.caValueName = "long    " + "l" + self.caName;
            elif self.cType[0] == 'D':
                self.caValueName = "double  " + "d" + self.caName
            self.fileFP.write("%s%s\n" % (" " * self.iDepth, self.caValueName))


    def endElement( self, name ):
        if lower(name) == "record" and self.caType == "Detail":
            self.iDepth -= 4
            self.bStructFg = False
            self.fileFP.write("%s} T_CSDT110001;\n" % " " * self.iDepth )

    def characters(self, contents):
        pass
def main():
    #tagName = raw_input( "Enter tag to search for: " )
    if os.path.exists("csdt110001.h") :
        os.remove("csdt110001.h")
    fp = open("csdt110001.h", "a+")
    try:
        parse( "csdt110001.xml", ParserHandler(fp) )
    except IOError, message:
        print "Error reading file:", message
    except SAXParseException, message:
        print "Error parsing file:", message
        
    fp.close()

if __name__ == "__main__":
    main()
